<template>
  <div class="product-table-container">
    <!-- 批量操作区域 -->
    <div class="bulk-actions" v-if="selectedProducts.length > 0">
      <span class="selected-count">已选择 {{ selectedProducts.length }} 个产品</span>
      <div class="action-buttons">
        <button class="btn-secondary" @click="handleBulkChangeStatus('active')">批量上架</button>
        <button class="btn-secondary" @click="handleBulkChangeStatus('inactive')">批量下架</button>
        <button class="btn-danger" @click="handleBulkDelete">批量删除</button>
      </div>
    </div>

    <!-- 表格主体 -->
    <div class="table-wrapper">
      <table class="product-table">
        <thead>
          <tr>
            <th class="checkbox-column">
              <input
                type="checkbox"
                :checked="isAllSelected"
                :indeterminate="isIndeterminate"
                @change="toggleSelectAll"
              />
            </th>
            <th class="image-column" stype="width: 120px">产品图片</th>
            <th
              class="sortable"
              :class="{
                active: sortBy === 'name',
                asc: sortOrder === 'asc',
                desc: sortOrder === 'desc',
              }"
              @click="sort('name')"
            >
              产品名称 <i class="fas fa-sort"></i>
            </th>
            <th
              class="price-column sortable"
              :class="{
                active: sortBy === 'originalPrice',
                asc: sortOrder === 'asc',
                desc: sortOrder === 'desc',
              }"
              @click="sort('originalPrice')"
            >
              原价 <i class="fas fa-sort"></i>
            </th>
            <th
              class="price-column sortable"
              :class="{
                active: sortBy === 'price',
                asc: sortOrder === 'asc',
                desc: sortOrder === 'desc',
              }"
              @click="sort('price')"
            >
              折扣价 <i class="fas fa-sort"></i>
            </th>
            <th>分类</th>
            <th
              class="number-column sortable"
              :class="{
                active: sortBy === 'stock',
                asc: sortOrder === 'asc',
                desc: sortOrder === 'desc',
              }"
              @click="sort('stock')"
            >
              库存 <i class="fas fa-sort"></i>
            </th>
            <th
              class="number-column sortable"
              :class="{
                active: sortBy === 'sales',
                asc: sortOrder === 'asc',
                desc: sortOrder === 'desc',
              }"
              @click="sort('sales')"
            >
              销量 <i class="fas fa-sort"></i>
            </th>
            <th>状态</th>
            <th class="actions-column">操作</th>
          </tr>
        </thead>
        <tbody>
          <template v-if="loading">
            <tr class="loading-row">
              <td colspan="10" class="text-center">
                <div class="loading-spinner"><i class="fas fa-spinner fa-spin"></i> 加载中...</div>
              </td>
            </tr>
          </template>
          <template v-else-if="sortedProducts.length === 0">
            <tr class="empty-row">
              <td colspan="10" class="text-center">
                {{ emptyText || '暂无产品数据' }}
              </td>
            </tr>
          </template>
          <template v-else>
            <tr v-for="product in paginatedProducts" :key="product.id" class="product-row">
              <td class="checkbox-column">
                <input
                  type="checkbox"
                  :checked="isSelected(product)"
                  @change="toggleSelect(product)"
                />
              </td>
              <td class="image-column">
                <div class="product-image" @click="previewImage(product.image)">
                  <img :src="product.head_img && product.head_img[0]" :alt="product.name" />
                </div>
              </td>
              <td class="product-name">{{ product.name }}</td>
              <td class="price-column">¥{{ formatPrice(product.originalPrice) }}</td>
              <td class="price-column">
                <span class="discount-price">¥{{ formatPrice(product.price) }}</span>
                <span v-if="product.price < product.originalPrice" class="discount-badge">
                  {{ calculateDiscount(product.price, product.originalPrice) }}折
                </span>
              </td>
              <td>
                <span class="category-badge">{{ product.category }}</span>
              </td>
              <td class="number-column">{{ product.stock }}</td>
              <td class="number-column">{{ product.sales }}</td>
              <td>
                <span
                  class="status-badge"
                  :class="{
                    active: product.status === 'active',
                    inactive: product.status === 'inactive',
                  }"
                >
                  {{ product.status === 'active' ? '上架' : '下架' }}
                </span>
              </td>
              <td class="actions-column">
                <div class="action-buttons">
                  <button class="action-btn edit-btn" @click="editProduct(product)" title="编辑">
                    <i class="fas fa-edit"></i>
                  </button>
                  <button
                    class="action-btn toggle-btn"
                    :class="{
                      unpublish: product.status === 'active',
                      publish: product.status === 'inactive',
                    }"
                    @click="toggleStatus(product)"
                    :title="product.status === 'active' ? '下架' : '上架'"
                  >
                    <i
                      :class="[product.status === 'active' ? 'fas fa-eye-slash' : 'fas fa-eye']"
                    ></i>
                  </button>
                  <button
                    class="action-btn delete-btn"
                    @click="deleteProduct(product)"
                    title="删除"
                  >
                    <i class="fas fa-trash-alt"></i>
                  </button>
                </div>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-wrapper" v-if="!loading && totalPages > 1">
      <div class="pagination">
        <button
          class="page-btn prev-btn"
          :disabled="currentPage === 1"
          @click="goToPage(currentPage - 1)"
        >
          <i class="fas fa-chevron-left"></i>
        </button>

        <template v-for="page in displayedPages" :key="page">
          <button v-if="page === '...'" class="page-btn ellipsis" disabled>...</button>
          <button
            v-else
            class="page-btn"
            :class="{ active: currentPage === page }"
            @click="goToPage(page)"
          >
            {{ page }}
          </button>
        </template>

        <button
          class="page-btn next-btn"
          :disabled="currentPage === totalPages"
          @click="goToPage(currentPage + 1)"
        >
          <i class="fas fa-chevron-right"></i>
        </button>
      </div>

      <div class="page-size-selector">
        <span>每页显示:</span>
        <select v-model="pageSize" @change="handlePageSizeChange">
          <option :value="10">10条</option>
          <option :value="20">20条</option>
          <option :value="50">50条</option>
        </select>
      </div>
    </div>

    <!-- 图片预览Modal -->
    <div class="image-preview-modal" v-if="showImagePreview" @click.self="closeImagePreview">
      <div class="preview-content">
        <img :src="previewImageUrl" alt="产品预览" />
        <button class="close-btn" @click="closeImagePreview">
          <i class="fas fa-times"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'

// 定义产品类型
interface Product {
  id: string
  name: string
  image: string
  originalPrice: number
  price: number
  category: string
  stock: number
  sales: number
  status: 'active' | 'inactive'
  description?: string
}

// 定义组件属性
const props = defineProps<{
  products: Product[]
  loading?: boolean
  emptyText?: string
}>()

// 定义组件事件
const emit = defineEmits<{
  (e: 'edit', product: Product): void
  (e: 'delete', product: Product): void
  (e: 'toggle-status', product: Product): void
  (e: 'bulk-delete', selectedProducts: Product[]): void
  (e: 'bulk-status-change', selectedProducts: Product[], status: 'active' | 'inactive'): void
}>()

// 排序状态
const sortBy = ref<keyof Product | ''>('')
const sortOrder = ref<'asc' | 'desc'>('asc')

// 分页状态
const currentPage = ref(1)
const pageSize = ref(10)

// 选中产品
const selectedProducts = ref<Product[]>([])

// 图片预览
const showImagePreview = ref(false)
const previewImageUrl = ref('')

// 监听产品变化，重置分页
watch(
  () => props.products,
  () => {
    currentPage.value = 1
    selectedProducts.value = []
  },
  { deep: true },
)

// 计算排序后的产品
const sortedProducts = computed(() => {
  if (!sortBy.value) return [...props.products]

  return [...props.products].sort((a, b) => {
    const aValue = a[sortBy.value as keyof Product]
    const bValue = b[sortBy.value as keyof Product]

    if (typeof aValue === 'string' && typeof bValue === 'string') {
      return sortOrder.value === 'asc' ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue)
    }

    // 数字比较
    if (typeof aValue === 'number' && typeof bValue === 'number') {
      return sortOrder.value === 'asc' ? aValue - bValue : bValue - aValue
    }

    return 0
  })
})

// 计算分页后的产品
const paginatedProducts = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return sortedProducts.value.slice(startIndex, endIndex)
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(sortedProducts.value.length / pageSize.value) || 1
})

// 生成显示的页码数组，添加省略号
const displayedPages = computed(() => {
  const totalPagesCount = totalPages.value
  const currentPageValue = currentPage.value
  const result = []

  // 总是显示第一页
  result.push(1)

  // 计算中间的页码
  if (currentPageValue > 3) {
    result.push('...')
  }

  for (
    let i = Math.max(2, currentPageValue - 1);
    i <= Math.min(totalPagesCount - 1, currentPageValue + 1);
    i++
  ) {
    result.push(i)
  }

  // 添加到最后一页之前的省略号
  if (currentPageValue < totalPagesCount - 2) {
    result.push('...')
  }

  // 总是显示最后一页（如果不是只有一页）
  if (totalPagesCount > 1) {
    result.push(totalPagesCount)
  }

  return result
})

// 全选状态
const isAllSelected = computed(() => {
  return props.products.length > 0 && selectedProducts.value.length === props.products.length
})

// 部分选中状态
const isIndeterminate = computed(() => {
  return selectedProducts.value.length > 0 && selectedProducts.value.length < props.products.length
})

// 排序方法
function sort(column: keyof Product) {
  if (sortBy.value === column) {
    // 如果已经在排序这列，切换排序方向
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    // 切换到新列，默认升序
    sortBy.value = column
    sortOrder.value = 'asc'
  }

  // 排序后回到第一页
  currentPage.value = 1
}

// 跳转到指定页面
function goToPage(page: number) {
  currentPage.value = page
}

// 处理每页显示数量变化
function handlePageSizeChange() {
  // 切换每页数量后回到第一页
  currentPage.value = 1
}

// 选择产品
function toggleSelect(product: Product) {
  const index = selectedProducts.value.findIndex((p) => p.id === product.id)
  if (index === -1) {
    selectedProducts.value.push(product)
  } else {
    selectedProducts.value.splice(index, 1)
  }
}

// 全选/取消全选
function toggleSelectAll() {
  if (isAllSelected.value) {
    selectedProducts.value = []
  } else {
    selectedProducts.value = [...props.products]
  }
}

// 检查产品是否已选中
function isSelected(product: Product) {
  return selectedProducts.value.some((p) => p.id === product.id)
}

// 批量操作
function handleBulkDelete() {
  if (!selectedProducts.value.length) return
  emit('bulk-delete', selectedProducts.value)
  selectedProducts.value = []
}

function handleBulkChangeStatus(status: 'active' | 'inactive') {
  if (!selectedProducts.value.length) return
  emit('bulk-status-change', selectedProducts.value, status)
  selectedProducts.value = []
}

// 单个产品操作
function editProduct(product: Product) {
  emit('edit', product)
}

function deleteProduct(product: Product) {
  emit('delete', product)
}

function toggleStatus(product: Product) {
  emit('toggle-status', product)
}

// 格式化价格
function formatPrice(price: number | null | undefined) {
  // 如果价格为null或undefined，返回'0.00'
  if (price === null || price === undefined) {
    return '0.00'
  }
  return price.toFixed(2)
}

// 计算折扣
function calculateDiscount(
  discountPrice: number | null | undefined,
  originalPrice: number | null | undefined,
) {
  // 如果价格为null或undefined，返回默认值10
  if (
    discountPrice === null ||
    discountPrice === undefined ||
    originalPrice === null ||
    originalPrice === undefined ||
    originalPrice <= 0
  ) {
    return 10
  }
  const discount = (discountPrice / originalPrice) * 10
  return discount.toFixed(1)
}

// 图片预览
function previewImage(imageUrl: string) {
  previewImageUrl.value = imageUrl
  showImagePreview.value = true
}

function closeImagePreview() {
  showImagePreview.value = false
}
</script>

<style scoped>
.product-table-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
}

/* 批量操作区域 */
.bulk-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f4f6fa;
  border-bottom: 1px solid #e5e9f2;
}

.selected-count {
  font-weight: 500;
  color: #3e4c59;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

/* 表格样式 */
.table-wrapper {
  overflow-x: auto;
  width: 100%;
}

.product-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.product-table thead th {
  background-color: #f9fafb;
  color: #4b5563;
  font-weight: 600;
  text-align: left;
  padding: 14px 16px;
  border-bottom: 1px solid #e5e9f2;
  position: sticky;
  top: 0;
  z-index: 1;
}

.product-table tbody td {
  padding: 14px 16px;
  border-bottom: 1px solid #e5e9f2;
  color: #1f2937;
  vertical-align: middle;
}

/* 排序列样式 */
th.sortable {
  cursor: pointer;
  user-select: none;
}

th.sortable:hover {
  background-color: #f1f5f9;
}

th.sortable i {
  margin-left: 5px;
  opacity: 0.3;
}

th.active {
  color: #1a73e8;
}

th.active i {
  opacity: 1;
}

th.asc i:before {
  content: '\f0de'; /* 向上箭头 */
}

th.desc i:before {
  content: '\f0dd'; /* 向下箭头 */
}

/* 行悬停效果 */
.product-row:hover {
  background-color: #f9fafb;
}

/* 图片列样式 */
.image-column {
  width: 80px;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  background-color: #f9fafb;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.2s ease;
}

.product-image:hover img {
  transform: scale(1.1);
}

/* 产品名称样式 */
.product-name {
  font-weight: 500;
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 价格列样式 */
.price-column {
  min-width: 90px;
}

.discount-price {
  color: #f43f5e;
  font-weight: 500;
}

.discount-badge {
  margin-left: 5px;
  background-color: #fff1f2;
  color: #e11d48;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  font-weight: 500;
}

/* 分类标签 */
.category-badge {
  background-color: #ecfdf5;
  color: #047857;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 500;
}

/* 状态标签 */
.status-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background-color: #d1fae5;
  color: #065f46;
}

.status-badge.inactive {
  background-color: #fee2e2;
  color: #b91c1c;
}

/* 操作按钮样式 */
.actions-column {
  width: 120px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
}

.action-btn {
  width: 32px;
  height: 32px;
  border-radius: 4px;
  border: none;
  background-color: transparent;
  color: #6b7280;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background-color: #f3f4f6;
}

.edit-btn:hover {
  color: #1a73e8;
}

.toggle-btn.publish:hover {
  color: #059669;
}

.toggle-btn.unpublish:hover {
  color: #f59e0b;
}

.delete-btn:hover {
  color: #ef4444;
}

/* 加载状态 */
.loading-row {
  height: 200px;
}

.loading-spinner {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6b7280;
  gap: 8px;
}

/* 空数据状态 */
.empty-row {
  height: 200px;
}

.text-center {
  text-align: center;
}

/* 复选框样式 */
.checkbox-column {
  width: 40px;
  text-align: center;
}

/* 数字列样式 */
.number-column {
  text-align: right;
  min-width: 80px;
}

/* 分页样式 */
.pagination-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-top: 1px solid #e5e9f2;
}

.pagination {
  display: flex;
  gap: 4px;
}

.page-btn {
  min-width: 36px;
  height: 36px;
  border-radius: 4px;
  border: 1px solid #d1d5db;
  background-color: white;
  color: #4b5563;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.page-btn:hover:not(:disabled) {
  background-color: #f3f4f6;
  border-color: #9ca3af;
}

.page-btn.active {
  background-color: #1a73e8;
  border-color: #1a73e8;
  color: white;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #4b5563;
  font-size: 14px;
}

.page-size-selector select {
  padding: 6px 8px;
  border-radius: 4px;
  border: 1px solid #d1d5db;
  background-color: white;
  color: #4b5563;
}

/* 图片预览模态框 */
.image-preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.preview-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
}

.preview-content img {
  max-width: 100%;
  max-height: 80vh;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

.close-btn {
  position: absolute;
  top: -40px;
  right: 0;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: none;
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

/* 公共按钮样式 */
.btn-primary,
.btn-secondary,
.btn-danger {
  padding: 8px 16px;
  border-radius: 4px;
  border: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-primary {
  background-color: #1a73e8;
  color: white;
}

.btn-primary:hover {
  background-color: #155db1;
}

.btn-secondary {
  background-color: #f3f4f6;
  color: #4b5563;
  border: 1px solid #d1d5db;
}

.btn-secondary:hover {
  background-color: #e5e7eb;
}

.btn-danger {
  background-color: #fee2e2;
  color: #dc2626;
}

.btn-danger:hover {
  background-color: #fecaca;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .product-name {
    max-width: 150px;
  }

  .action-buttons {
    flex-wrap: wrap;
  }
}

@media (max-width: 768px) {
  .page-size-selector {
    display: none;
  }

  .product-table thead th,
  .product-table tbody td {
    padding: 10px 12px;
  }

  .product-name {
    max-width: 120px;
  }
}
</style>
